package com.github.lee.core.common.view

import android.content.Context
import android.util.AttributeSet
import com.github.lee.core.common.R

class RatioImageView : androidx.appcompat.widget.AppCompatImageView {

    var standard = 0
    var ration = 0.0f

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context, attrs)
    }
    //===Desc:=========================================================

    private fun init(context: Context, attrs: AttributeSet?) {
        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.RatioImageView)
        standard = typedArray.getInt(R.styleable.RatioImageView_riv_standard, 0)
        ration = typedArray.getFloat(R.styleable.RatioImageView_riv_ratio, 0.0f)
        typedArray.recycle()
    }
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (standard == 0) {
            var hms = heightMeasureSpec
            val width = MeasureSpec.getSize(widthMeasureSpec)
            val widthMode = MeasureSpec.getMode(widthMeasureSpec)
            if ((widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST) && ration != 0.0f) {
                val height = width / ration
                hms = MeasureSpec.makeMeasureSpec(height.toInt(), MeasureSpec.EXACTLY)
            }
            super.onMeasure(widthMeasureSpec, hms)
        } else {
            var wms = widthMeasureSpec
            val height = MeasureSpec.getSize(heightMeasureSpec)
            val heightMode = MeasureSpec.getMode(widthMeasureSpec)
            if (heightMode == MeasureSpec.EXACTLY && ration != 0.0f) {
                val width = height * ration
                wms = MeasureSpec.makeMeasureSpec(width.toInt(), MeasureSpec.EXACTLY)
            }
            super.onMeasure(wms, heightMeasureSpec)
        }
    }

}